package indi.woniu.security;


import indi.woniu.entity.UserDo;
import indi.woniu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: GaN601
 * @Date: 2021/12/7 17:29
 * @Description: 自定义获取用户信息和角色信息
 */
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {
    private UserService userService;
    
    
    @Autowired
    public void setUserService(final UserService userService) {
        this.userService = userService;
    }
    
    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        // 根据用户名查询数据库
        UserDo userDo = userService.selectByName(username);
        if (userDo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        List<String> paths = userDo.getRole().getPaths();
        // 将用户名、密码和对应角色放入组件
        return User.withUsername(username).password(userDo.getPassword()).authorities(
                paths.toArray(new String[0])).roles(userDo.getRole().getName()).build();
    }
}
